package com.bing.mvc;

import com.bing.bean.WeiXinUser;
import com.bing.bean.weixin.OauthInfo;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by kaibb on 2014/10/1.
 */
public class WeiXinOauthInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(WeiXinOauthInterceptor.class);
    public static final String WEI_XIN_USER = "weiXinUser";
    private Lock lock = new ReentrantLock();
    @Autowired()
    private OauthInfo oauthInfo;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String weixinAuth = request.getParameter("weixinAuth");

        if (code != null && state != null && request.getSession().getAttribute(WEI_XIN_USER) == null) {
            logger.info("微信认证锁:");
            lock.lock();
            if (request.getSession().getAttribute(WEI_XIN_USER) == null) {
                logger.info("微信认证进行中:");
                WeiXinUser weiXinUser = oauthInfo.oauthWeiXin(code);
                request.getSession().setAttribute(WEI_XIN_USER, weiXinUser);
            }
            lock.unlock();
        } else if (weixinAuth != null && request.getSession().getAttribute(WEI_XIN_USER) == null) {
            logger.info("微信Oauth认证拦截器.......preHandle ");
            String url = request.getRequestURL().toString() + "?" + request.getQueryString();
            oauthInfo.setRedirect_uri(url);
            String codeUrl = oauthInfo.getCodeUrl();
            logger.info("GetCode Url:{}", codeUrl);
            response.setStatus(HttpStatus.SC_TEMPORARY_REDIRECT);
            response.addHeader("location", codeUrl);
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (request.getParameter("weixinAuth") != null) {
            logger.info("微信Oauth认证拦截器.......postHandle");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (request.getParameter("weixinAuth") != null) {
            logger.info("微信Oauth认证拦截器.......afterCompletion");
        }
    }
}
